package com.healthcloud.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.healthcloud.dao.FastdfsFileServerDao;
import com.healthcloud.entity.*;
import com.healthcloud.service.SysConfigService;
import com.healthcloud.service.VersionService;
import com.healthcloud.upload.FastDFSClient;
import com.healthcloud.utils.ApiRes;
import com.healthcloud.utils.PageParam;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import springfox.documentation.annotations.ApiIgnore;

@ApiIgnore
@Controller
@RequestMapping(value = "/version")
public class VersionController {

    private static final Logger LOG = LoggerFactory.getLogger(VersionController.class);

	@Autowired
    private VersionService versionService;

	@Autowired
	private SysConfigService sysConfigService;

	@Autowired
	private FastdfsFileServerDao fastdfsFileServerDao;

    private final String saveLinuxPath="/usr/local/tomcat/webapps/appdownloads/poct"; //linux保存路径

    private final String saveWinPath="D://appdownloads/poct";//windows保存路径

    private final String saveWinPathImg="D://Program Files/apache-tomcat-7.0.68/webapps/appdownloads";

    @RequestMapping(value = "/toVersionMgr",method=RequestMethod.GET)
    public String toVersionMgr(){
        return "newframe/versionmgr";
    }

    @RequestMapping(value = "/version")
    public @ResponseBody
    Map<String, Object>  searchVersion(VersionEntity bean, Model model, @ModelAttribute("pageParam")PageParam pageParam){
        List<VersionEntity> list = versionService.search(bean, pageParam);
        int count = versionService.count(bean);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("dataList", list);
        map.put("iTotalRecords", count);
        map.put("iTotalDisplayRecords", count);
        map.put("sEcho", pageParam.getsEcho());
        return map;
    }

    @RequestMapping(value = "/toUpdateVersion",method=RequestMethod.GET)
    public String toUpdateVersion(String id,String method, Model model){
    	VersionEntity entity = null;
    	if("2".equals(method)){
    		entity = versionService.get(Integer.parseInt(id));
    	}
    	model.addAttribute("entity", entity);
        return "newframe/update_version";
    }

    @RequestMapping(value = "/updateVersion")
    public @ResponseBody
    ApiRes updateVersion(VersionEntity bean) {
    	if(bean.getId() == null){
    		versionService.save(bean);
    	}else{
    		versionService.update(bean);
    	}
        return new ApiRes(true,null,null,String.valueOf(bean.getId()));
    }

    @RequestMapping(value = "/deleteVersion")
    public @ResponseBody
    ApiRes deleteVersion(String[] ids) {
        // TODO 参数检测
        for (int i=0; i<ids.length; i++){
            Integer l = null;
            try {
                l = Integer.valueOf(ids[i]);
                versionService.delete(l);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    	return new ApiRes(true,null,null,null);
    }

    @RequestMapping(value = "/uploadVersion")
    public @ResponseBody
    ApiRes uploadVersion(@RequestParam MultipartFile file, HttpServletRequest request, String id) {
    	if(file.isEmpty()){
    		return new ApiRes(true,null,null,null);
    	}
    	String savePath = "";
    	if(System.getProperties().getProperty("os.name").startsWith("Windows")){
    		savePath = saveWinPath;
    	}else{
    		savePath = saveLinuxPath;
    	}
        LOG.info(file.getOriginalFilename());
        LOG.info("文件名称: " + file.getOriginalFilename());
        LOG.info("文件长度: " + file.getSize());
        LOG.info("文件类型: " + file.getContentType());
        LOG.info("========================================");
		VersionEntity bean = versionService.get(Integer.parseInt(id));

		if(!file.getOriginalFilename().endsWith(".apk") && !file.getOriginalFilename().endsWith(".hex")){
			return new ApiRes(false,null,"请上传正确的文件格式！",null);
		}
		String fileName = file.getOriginalFilename();
		String saveName = fileName.substring(0, fileName.length() - 4) + "_"
				+ bean.getChildVersion()
				+ fileName.substring(fileName.length() - 4, fileName.length());
		try {
			FileUtils.copyInputStreamToFile(file.getInputStream(), new File(savePath, saveName));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
            LOG.error(e.getMessage());
		}

        CommonsMultipartFile cf = (CommonsMultipartFile)file;
        DiskFileItem fi = (DiskFileItem) cf.getFileItem();
        File fl = fi.getStoreLocation();
        String fileId =FastDFSClient.uploadFile(fl,saveName);


//        String appAdress =  "http://cloud.nbmedicalsystem.com/appdownloads/poct/"+saveName;
		String appAdress =  "https://cloud.nbmedicalsystem.com/medical-cloud/version/downVersion?fileId="+fileId+"&fileName="+fileName;
		bean.setAppAddress(appAdress);
		versionService.updateVersionAddress(bean);

        return new ApiRes(true,null,null,null);
    }


    /**
     * 下载
     */
    @RequestMapping("/downVersion")
    public void code(HttpServletResponse response, @RequestParam("fileId") String fileId,@RequestParam("fileName") String fileName){
        try {

            InputStream inputStream = FastDFSClient.downloadFile(fileId);
            byte[] data = IOUtils.toByteArray(inputStream);


            response.reset();
//            response.setHeader("Content-Disposition", "attachment; filename="+fileName);
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream; charset=UTF-8");

            IOUtils.write(data, response.getOutputStream());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/toVersionNumMgr",method=RequestMethod.GET)
    public String toVersionNumMgr(){
        return "newframe/versionnummgr";
    }
    @RequestMapping(value = "/searchVersionNum")
    public @ResponseBody
    Map<String, Object>  searchVersionNum(SysConfigEntity bean,Model model, @ModelAttribute("pageParam")PageParam pageParam){
        bean.setConfigName("version");
        List<SysConfigEntity> list = sysConfigService.queryList(bean, pageParam);
        int count = sysConfigService.queryTotal(bean);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("dataList", list);
        map.put("iTotalRecords", count);
        map.put("iTotalDisplayRecords", count);
        map.put("sEcho", pageParam.getsEcho());
        return map;
    }

    @RequestMapping(value = "/toUpdateVersionNum",method=RequestMethod.GET)
    public String toUpdateVersionNum(String id,String method, Model model){
        SysConfigEntity entity = null;
    	if("2".equals(method)){
    		entity = sysConfigService.queryObjectByid(Long.parseLong(id));
    	}
    	model.addAttribute("entity", entity);
        return "newframe/update_versionnum";
    }

    @RequestMapping(value = "/updateVersionNum")
    public @ResponseBody
    ApiRes updateVersionNum(SysConfigEntity bean) {
    	if(bean.getId() == null){
    		bean.setConfigName("version");
            sysConfigService.save(bean);
    	}else{
            sysConfigService.update(bean);
    	}
        return new ApiRes(true,null,null,String.valueOf(bean.getId()));
    }
}
